#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: xmind_get_case_list.py
# Author: ChenChangSong
# Date: 2025-08-24

"""
功能描述: 获取xmind文件中的用例列表
"""

import sys
import os
import re
import json
import xmindparser
# 不再添加项目路径到环境
from comm.common_code import *

def process_xmind(xmind_path, level=0):
    """处理单个xmind文件
    """

    # 先判断输入的level参数是否有效
    if 1<= level < 3:
        logger.error(f'输入的level参数 {level} 小于3，不符合要求')
        return
    elif level == 0:
        pass
    # 解析xmind文件内容
    xmind_content = xmindparser.xmind_to_dict(xmind_path)
    
    # 提取 topic 下的 title 字段
    json_str = xmind_content[0]['topic']['title']
    
    # 需求id
    if '需求ID' in json_str:
        pattern = r'需求ID[：:]\s*(\d+)'
        match = re.search(pattern, json_str)
        requirement_id = match.group(1) if match else None
        print(f'需求ID：{requirement_id}')
    elif '需求id' in json_str:
        pattern = r'需求id[：:]\s*(\d+)'
        match = re.search(pattern, json_str)
        requirement_id = match.group(1) if match else None
        logger.info(f'需求id：{requirement_id}')
    elif 'requirement_id' in json_str:
        try:
            data_list = json.loads(json_str)
            requirement_id = data_list['requirement_id']
            print(f'需求ID：{requirement_id}')
        except json.JSONDecodeError:
            requirement_id = ''
            print('需求ID格式不正确,请手动填写')
        print(f'需求ID：{requirement_id}')
    else:
        requirement_id = ''
        print('需求ID格式不正确,请手动填写')
    
    results = []  # 存储提取结果

    def traverse(node, current_path, module_name):
        """递归遍历xmind节点
        :param node: 当前节点
        :param current_path: 当前路径列表
        :param module_name: 所属模块名
        """
        # 先判断需求ID是否存在
        # if not requirement_id:
        #     print('需求ID不存在，无法继续执行')
        #     return
            
        if 'topics' in node:
            for topic in node['topics']:
                new_path = current_path + [topic['title']]
                if 'topics' in topic:
                    traverse(topic, new_path, module_name)
                else:
                    # 提取叶子节点作为测试用例[需求ID,用例目录,用例名称,用例步骤,预期结果]
                    # 根据level参数确定case_directory的生成方式
                    if level >= 3 and len(new_path) > level + 1:
                        # 当level大于等于3且节点数足够时，取前level个节点
                        case_directory = module_name + "-" + "-".join(new_path[:level-1])
                    elif len(new_path) == 2 or len(new_path) == 1:
                        case_directory = module_name
                    else:
                        case_directory = module_name + "-" + "-".join(new_path[:-2])
                    case_name = new_path[-2] + "-" + new_path[-1]
                    # case_steps = " >> ".join(new_path[:-1]) if len(new_path) > 1 else ""
                    case_steps = module_name + " >> " + " >> ".join(new_path[:-1])
                    one_case = [requirement_id, case_directory, case_name, case_steps, new_path[-1]]
                    print(one_case)
                    results.append(one_case)
    
    # 处理每个模块
    for module in xmind_content[0]['topic']['topics']:
        module_name = module['title']
        if 'topics' in module:
            for func in module['topics']:
                traverse(func, [func['title']], module_name)
    print("results：\n",results)
    return results
if __name__ == '__main__':

    # 获取当前脚本文件的目录
    from ui_code.common_ui import get_project_root
    xmind_dir_path = get_project_root() / "files" / "【示例】商品详情qwer12345.xmind"
    
    level = 0
    # 调用函数处理xmind文件
    process_xmind(str(xmind_dir_path), level)
